package com.dhu.controller;

import com.alibaba.fastjson.JSONObject;
import com.dhu.dao.FileMapper;
import com.dhu.dao.UserMapper;
import com.dhu.pojo.FileBean;
import com.dhu.pojo.User;
import com.dhu.service.FileService;
import com.dhu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;

@CrossOrigin
@RestController
public class FileController {
    @Autowired
    private FileService fileService;
    @Autowired
    private UserService userService;

    @PostMapping("/upload")
    public String importData(int id, String token, MultipartFile file, HttpServletRequest req) {
        //FileBean fileBean = new FileBean();
        try {
            JSONObject res = new JSONObject();
            String realPath = ResourceUtils.getURL("classpath:").getPath() + "static";
            if (!file.isEmpty()) {
                res.put("code", "404");
                res.put("message", "上传文件名为空");
            }
            String oldName = file.getOriginalFilename();
            String newName = UUID.randomUUID().toString() + oldName;
            //fileBean.setFilename(newName);
            //fileBean.setPath(realPath);
            //fileBean.setType(file.getContentType());
            //fileBean.setSize(file.getSize());

            file.transferTo(new File(realPath, newName));
            if (userService.updateUserAvatar(newName, id, token) == 1) {
                res.put("code", "200");
                res.put("message", "上传文件成功");
            } else {
                res.put("code", "403");
                res.put("message", "上传文件失败");
            }
            return res.toJSONString();
        } catch (IOException e) {
            JSONObject res = new JSONObject();
            res.put("code", "402");
            res.put("message", "上传文件失败");
            return res.toJSONString();
        }
    }
}
